/**
 *  Copyright (c)  2011-2020 Panguso, Inc.
 *  All rights reserved.
 *
 *  This software is the confidential and proprietary information of Panguso, 
 *  Inc. ("Confidential Information"). You shall not
 *  disclose such Confidential Information and shall use it only in
 *  accordance with the terms of the license agreement you entered into with Panguso.
 */
package com.lazy.utils.utils;


import com.lazy.utils.exception.ProgramException;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 常用的字符串处理类
 */
public final class StringUtil {
//	private static final SecureRandom sr = new SecureRandom();

    private static String PREFIX = "\\u";

    private StringUtil() {
    }

    /**
     * @param list 列表
     * @return
     * @author liufengyu
     * @date 2013-1-24
     */
    public static String getAllWapPushid(List<?> list) {
        // modified by zhangzg
        StringBuffer wapPushMessageids = new StringBuffer(128);

        if (list.size() > 0) {
            Object wapPushMessageid = list.get(0);
            wapPushMessageids.append(wapPushMessageid);
        }
        for (int i = 1; i < list.size(); i++) {
            Object wapPushMessageid = list.get(i);
            wapPushMessageids.append(",");
            wapPushMessageids.append(wapPushMessageid);
        }
        return wapPushMessageids.toString();
    }

    /**
     * 取域名
     *
     * @param url 要取域名的url
     */
    public static String getDomainName(String url) {
        String domainName = "";
        String pattern = "[^//]*?\\.(com|cn|net|org|biz|info|cc|tv)";
        pattern = "(?<=http://|\\.)[^.]*?\\.(com|cn|net|org|biz|info|cc|tv)";
        Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
        Matcher matcher = p.matcher(url);
        boolean match = matcher.find();
        if (match) {
            domainName = matcher.group();
        }
        return domainName;
    }

    /**
     * 根据|分隔的字符串拼成一个列表
     *
     * @param str |分隔的字符串
     */
    public static List<String> getListByStr(String str) {
        List<String> list = new ArrayList<String>();
        StringBuffer sb = new StringBuffer();
        String tempStr = null;
        char[] strChars = str.toCharArray();
        for (int i = 0; i < strChars.length; i++) {
            if (strChars[i] != '|' && i != strChars.length - 1) {
                sb.append(strChars[i]);
            } else {
                tempStr = sb.toString();
                String[] segArray = tempStr.split(":");
                if (segArray.length > 1) {
                    list.add(segArray[1]);
                }
                sb = new StringBuffer();
            }
        }
        return list;
    }

    /**
     * 根据指定分隔符的字符串拼成一个列表
     *
     * @param str       分隔的字符串
     * @param seperator 分隔符
     */
    public static List<String> getListByStr(String str, char seperator) {
        List<String> list = new ArrayList<String>();
        StringBuffer sb = new StringBuffer();
        String tempStr = null;
        char[] strChars = str.toCharArray();
        for (int i = 0; i < strChars.length; i++) {
            if (strChars[i] != seperator && i != strChars.length - 1) {
                sb.append(strChars[i]);
            } else {
                if (i == strChars.length - 1 && strChars[strChars.length - 1] != seperator) {
                    sb.append(strChars[i]);
                }
                tempStr = sb.toString();
                list.add(tempStr);
                sb = new StringBuffer();
            }
        }
        return list;
    }

    /**
     * 根据|分隔的字符串拼成一个列表
     *
     * @param str |分隔的字符串
     */
    public static List<String> getListByStr2(String str) {
        List<String> list = new ArrayList<String>();
        StringBuffer sb = new StringBuffer();
        String tempStr = null;
        char[] strChars = str.toCharArray();
        for (int i = 0; i < strChars.length; i++) {
            if (strChars[i] != '|' && i != strChars.length - 1) {
                sb.append(strChars[i]);
            } else {
                tempStr = sb.toString();
                String[] segArray = tempStr.split(":");
                if (segArray.length > 0) {
                    list.add(segArray[0]);
                }
                sb = new StringBuffer();
            }
        }
        return list;
    }

    /**
     * 根据|分隔的字符串拼成一个列表
     *
     * @param str |分隔的字符串
     */
    public static List<String> getListByStrForBook(String str) {
        List<String> list = new ArrayList<String>();
        StringBuffer sb = new StringBuffer();
        String tempStr = null;
        char[] strChars = str.toCharArray();
        for (int i = 0; i < strChars.length; i++) {
            if (strChars[i] != '|' && i != strChars.length - 1) {
                sb.append(strChars[i]);
            } else {
                tempStr = sb.toString();
                String[] segArray = tempStr.split(":");
                if (segArray.length > 0) {
                    list.add(tempStr);
                }
                sb = new StringBuffer();
            }
        }
        return list;
    }

    /**
     * 根据|分隔的字符串拼成一个列表
     *
     * @param str |分隔的字符串
     */
    public static List<String> getListByStr3(String str) {
        List<String> list = new ArrayList<String>();
        StringBuffer sb = new StringBuffer();
        String tempStr = null;
        char[] strChars = str.toCharArray();
        for (int i = 0; i < strChars.length; i++) {
            if (strChars[i] != ',' && i != strChars.length - 1) {
                sb.append(strChars[i]);
            } else {
                tempStr = sb.toString();
                String[] segArray = tempStr.split(":");
                if (segArray.length > 0) {
                    list.add(segArray[0]);
                }
                sb = new StringBuffer();
            }
        }
        return list;
    }

    /**
     * 判断一个字符串是否是null或者空格或者空
     *
     * @param str 字符串
     * @return
     */
    public static boolean isEmpty(String str) {
        if (str != null && str.trim().length() > 0) {
            return false;
        }
        return true;
    }

    /**
     * 如果一个字符串为null，则转化为“”；否则，返回本身
     *
     * @param str 字符串
     * @return
     */
    public static String nullToStr(String str) {
        return str == null ? "" : str;
    }

    /**
     * <p>
     * 字符的前后几位保持不变，其它字符用代替字符替换（先替换前几位字符，后替换后几位字符）
     * </p>
     *
     * @param str       原字符
     * @param prefix    前几位(0,表示不做替换）
     * @param postfix   后几位(0,表示不做替换）
     * @param character 替换字符(若替换字符为一位，则保持长度不变)
     * @return 替换后的字符
     */
    public static String stringSwitch(String str, int prefix, int postfix, String character) {
        if (prefix < 0 || postfix < 0) {
            return str;
        }
        if (prefix == 0 && postfix == 0) {
            return str;
        }
        if (str != null && str.trim().length() > 0) {
            StringBuffer buf = new StringBuffer();
            int argsLength = str.length();
            // 保证被替换的长度大于原字符长度
            if (argsLength > prefix + postfix) {
                if (prefix != 0) {
                    String stringPrefix = str.substring(0, prefix);
                    buf.append(stringPrefix);
                }
                for (int i = prefix; i < argsLength - postfix; i++) {
                    buf.append(character);
                }
                if (postfix != 0) {
                    String stringPostfix = str.substring(argsLength - postfix);
                    buf.append(stringPostfix);
                }
                return buf.toString();
            } else {
                return str;
            }
        }
        return null;
    }

    /**
     * 生成一个定长的纯0字符串
     *
     * @param length 字符串长度
     * @return 纯0字符串
     */
    public static String generateZeroStr(int length) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            sb.append('0');
        }
        return sb.toString();
    }

    /**
     * 根据数字生成一个定长的字符串，长度不够前面补0
     *
     * @param num       数字
     * @param fixdlenth 字符串长度
     * @return 定长的字符串
     */
    public static String toFixdLengthStr(long num, int fixdlenth) {
        StringBuffer sb = new StringBuffer();
        String strNum = String.valueOf(num);
        if (fixdlenth - strNum.length() >= 0) {
            sb.append(generateZeroStr(fixdlenth - strNum.length()));
        } else {
            throw new ProgramException("将数字" + num + "转化为长度为" + fixdlenth + "的字符串发生异常！");
        }
        sb.append(strNum);
        return sb.toString();
    }

    /**
     * 根据数字生成一个定长的字符串，长度不够前面补0
     *
     * @param num       数字
     * @param fixdlenth 字符串长度
     * @return 定长的字符串
     */
    public static String toFixdLengthStr(int num, int fixdlenth) {
        StringBuffer sb = new StringBuffer();
        String strNum = String.valueOf(num);
        if (fixdlenth - strNum.length() >= 0) {
            sb.append(generateZeroStr(fixdlenth - strNum.length()));
        } else {
            throw new ProgramException("将数字" + num + "转化为长度为" + fixdlenth + "的字符串发生异常！");
        }
        sb.append(strNum);
        return sb.toString();
    }

//
//	/**
//	 * 
//	 * 产生任意给定长度的随纯机数字字符串。
//	 * <p>
//	 * </p>
//	 * 
//	 * @param iLength
//	 *            产生随机数的位数
//	 * @return 给定位数的随机数
//	 */
//	public static String getRandomIntNum(int iLength) {
//		sr.setSeed(System.currentTimeMillis());
//		StringBuffer sb = new StringBuffer();
//		for (int i = 0; i < iLength; i++) {
//			sb.append(Math.abs(sr.nextInt(10)));
//		}
//		return sb.toString();
//	}
//
//	public static int getRandomIntNumByMax(int max) {
//		sr.setSeed(System.currentTimeMillis());
//		return sr.nextInt(max);
//	}

    /**
     * 按字节长度截取字符串
     *
     * @param str     将要截取的字符串参数
     * @param toCount 截取的字节长度
     * @param more    字符串末尾补上的字符串
     * @return 返回截取后的字符串
     */
    public static String substring(String str, int toCount, String more) {
        int reInt = 0;
        String reStr = "";
        if (str == null) {
            return "";
        }
        char[] tempChar = str.toCharArray();
        for (int kk = 0; (kk < tempChar.length && toCount > reInt); kk++) {
            String s1 = String.valueOf(tempChar[kk]);
            byte[] b = s1.getBytes();
            reInt += b.length;
            reStr += tempChar[kk];
        }
        if (toCount == reInt || (toCount == reInt - 1)) {
            reStr += more;
        }
        return reStr;
    }

    /**
     * 将对象转换为字符串，如果对象为null，则返回null
     *
     * @param obj 对象
     * @return
     */
    public static String object2Str(Object obj) {
        if (obj == null) {
            return null;
        } else {
            return obj.toString();
        }
    }

    /**
     * filtertoHTML
     *
     * @param input String
     * @return input String
     * @author chenjiang
     */
    public static String filterToHtml(String input) {
        if (input == null || input.equals("")) {
            return input;
        }
        StringBuffer filtered = new StringBuffer(input.length());
        char c;
        for (int i = 0; i <= input.length() - 1; i++) {
            c = input.charAt(i);
            switch (c) {
                case '"':
                    filtered.append("&quot;");
                    break;
                case '&':
                    filtered.append("&amp;");
                    break;
                case '<':
                    filtered.append("&lt;");
                    break;
                case '>':
                    filtered.append("&gt;");
                    break;
                case ' ':
                    filtered.append("&#160;");
                    break;
//            case '|':
//                filtered.append("&brvbar;");
//                break;
                case 13:
                    filtered.append("<br/>");
                    break;
                default:
                    filtered.append(c);
            }
        }
        return (filtered.toString());
    }

    /**
     * 判断一个IP地址是否合法
     *
     * @param ip IP
     * @return
     * @author liufengyu
     */
    public static boolean isIPAddressCorrect(String ip) {
        String[] ips = ip.split("\\.");
        if (ips.length != 4) {
            return false;
        }
        for (int i = 0; i < ips.length; i++) {
            try {
                if (Integer.parseInt(ips[i]) > 255) {
                    return false;
                }
            } catch (NumberFormatException ex) {
                return false;
            }
        }
        return true;
    }

    /**
     * add by gongtao
     * <p/>
     * 检查传入的手机号码 是否 属于 中国移动的手机号码
     * </P>
     *
     * @param destmsisdn 手机号
     * @return true 是中国移动手机号码 false 不是中国移动手机号码
     * @throws Exception
     */
    public static boolean isCMCCmobile(String destmsisdn) {
        // 中国移动手机号码 段正则表达式
        String regEx = "^1((3[4-9])|(4[7])|(5[0-3|6-9])|(8[278]))[0-9]{8}$";
        Pattern pattern = Pattern.compile(regEx);
        Matcher m = pattern.matcher(destmsisdn); // 拿当前的手机号码与正则表达式去匹配
        boolean isCMCC = m.find(); // 匹配成功 的为中国移动手机号码
        return isCMCC;
    }

    /**
     * add by gongtao
     * <p/>
     * 将数组中重复的字符串 去除
     * </P>
     *
     * @param destmsisdns 手机号
     * @return
     */
    public static String removeSameDestmsisdn(String destmsisdns) {
        String tmp = null;
        StringBuffer sb = new StringBuffer();
        String[] destmsisdnArray = destmsisdns.split(",");
        if (destmsisdnArray == null || destmsisdnArray.length == 0) {
            return null;
        }
        ArrayList<String> resultList = new ArrayList<String>();
        for (int i = 0; i < destmsisdnArray.length; i++) {
            if (resultList.contains(destmsisdnArray[i])) {
                continue;
            } else {
                resultList.add(destmsisdnArray[i]);
            }
        }
        for (int i = 0; i < resultList.size(); i++) {
            sb.append(resultList.get(i));
            sb.append(",");
        }
        if (sb.length() > 0) {
            tmp = sb.substring(0, sb.length() - 1);
        } else {
            tmp = sb.toString();
        }
        return tmp;
    }

    /**
     * add by gongtao
     * <p>
     * 字符串的转换
     * </p>
     *
     * @param str 字符串
     * @return
     */
    public static String stringGBK(String str) {
        String s = "";
        try {
            if (str == null) {
                return null;
            }
            s = new String(str.getBytes("ISO-8859-1"), "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return s;
    }

    /**
     * 输入字符串是否中文
     *
     * @param str 字符串
     * @return
     * @author zhoulei
     */
    public static boolean isChinese(String str) {

        for (int i = 0; i < str.length(); i++) {
            if (!str.substring(i, i + 1).matches("[\\u4e00-\\u9fa5]+")) {
                return false;
            }
        }
        return true;
    }

    /**
     * 输入字符串是否有英文
     *
     * @param str 字符串
     * @return
     * @author zhoulei
     */
    public static boolean hasEnglish(String str) {

        for (int i = 0; i < str.length(); i++) {
            if (!str.substring(i, i + 1).matches("[a-zA-Z]+")) {
                return false;
            }
        }
        return true;
    }

    /**
     * 输入字符串是否有数字
     *
     * @param str 字符串
     * @return
     * @author zhoulei
     */
    public static boolean hasNumeral(String str) {

        for (int i = 0; i < str.length(); i++) {
            if (!str.substring(i, i + 1).matches("\\d+")) {
                return false;
            }
        }
        return true;
    }

    /**
     * 拆分字符串。
     *
     * @param src      字符串
     * @param splitter 分隔符
     * @return
     */
    public static List<String> split2List(String src, String splitter) {
        List<String> results = new ArrayList<String>();

        if (src == null) {
            return results;
        }
        String[] temp = src.split(splitter);
        for (int i = 0; i < temp.length; i++) {
            if (!temp[i].trim().equals("")) {
                results.add(temp[i].trim());
            }
        }

        return results;
    }

    /**
     * 定义字节（汉字、符号和英文字母的混合串）长度
     *
     * @param value 字符串
     * @return
     * @author liufengyu
     * @date 2013-1-24
     */
    public static int length(String value) {
        int valueLength = 0;
        String chinese = "[\u4e00-\u9fa5]";

        if (StringUtil.isEmpty(value)) {
            return 0;
        }

        for (int i = 0; i < value.length(); i++) {

            String temp = value.substring(i, i + 1);

            if (temp.matches(chinese)) {

                valueLength += 2;
            } else {

                valueLength += 1;
            }
        }
        return valueLength;
    }

    /**
     * 截取指定产度的字节
     *
     * @param value     字符串
     * @param endLength 长度
     * @return
     * @author liufengyu
     * @date 2013-1-24
     */
    public static String truncate(String value, int endLength) {
        int valueLength = 0;
        String chinese = "[\u4e00-\u9fa5]";

        StringBuffer sb = new StringBuffer();

        if (length(value) < endLength) {
            return value;
        }

        for (int i = 0; i < value.length(); i++) {
            String temp = value.substring(i, i + 1);
            if (temp.matches(chinese)) {
                valueLength += 2;
            } else {
                valueLength += 1;
            }
            if (valueLength > endLength) {
                break;
            } else {
                sb.append(temp);
            }
        }
        return sb.toString();
    }

    /**
     * 截取指定产度的字节
     *
     * @param value     字符串
     * @param maxLength 长度
     * @return
     * @author liufengyu
     * @date 2013-1-24
     */
    public static String truncateByMaxLength(String value, int maxLength) {
        int endLength = maxLength - 3;
        int valueLength = 0;
        String result = null;
        String chinese = "[\u4e00-\u9fa5]";

        StringBuffer sb = new StringBuffer();

        if (length(value) <= maxLength) {
            return value;
        }

        for (int i = 0; i < value.length(); i++) {
            String temp = value.substring(i, i + 1);
            if (temp.matches(chinese)) {
                valueLength += 2;
            } else {
                valueLength += 1;
            }
            if (valueLength > endLength) {
                break;
            } else {
                sb.append(temp);
            }
        }
        result = sb.toString() + "...";

        return result;
    }

    /**
     * 将一个List中的元素按照分隔符拼成一个字符串。
     *
     * @param list     列表
     * @param splitter 分隔符
     * @return
     */
    public static String list2Str(List<?> list, String splitter) {
        StringBuilder sb = new StringBuilder();

        if (list.size() > 0) {
            sb.append(list.get(0).toString());
        }
        for (int i = 1; i < list.size(); i++) {
            sb.append(splitter).append(list.get(i));
        }

        return sb.toString();
    }

    /**
     * 取得文件后缀名
     *
     * @param fileName 文件名
     * @return
     */
    public static String getFileSuffix(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    /**
     * 限制字符串输出500个字符以内
     *
     * @param value  字符串原值
     * @param length 截取的字符串长度
     * @return
     * @author fangqi
     * @date 2012-12-3
     */
    public static String limitTo(String value, int length) {
        if (value.length() > length) {
            value = value.substring(0, length);
            return value + " ...";
        }
        return value;
    }

    public static String gbEncoding(final String gbString) {
        char[] utfBytes = gbString.toCharArray();
        String unicodeBytes = "";
        for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) {
            String hexB = Integer.toHexString(utfBytes[byteIndex]);
            if (hexB.length() <= 2) {
                hexB = "00" + hexB;
            }
            unicodeBytes = unicodeBytes + "\\u" + hexB;
        }
        System.out.println("unicodeBytes is: " + unicodeBytes);
        return unicodeBytes;
    }

    private static char ascii2Char(String str) {
        if (str.length() != 6) {
            throw new IllegalArgumentException(
                    "Ascii string of a native character must be 6 character.");
        }
        if (!PREFIX.equals(str.substring(0, 2))) {
            throw new IllegalArgumentException(
                    "Ascii string of a native character must start with \"\\u\".");
        }
        String tmp = str.substring(2, 4);
        int code = Integer.parseInt(tmp, 16) << 8;
        tmp = str.substring(4, 6);
        code += Integer.parseInt(tmp, 16);
        return (char) code;
    }

    public static String native2Ascii(String str) {
        char[] chars = str.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
            sb.append(char2Ascii(chars[i]));
        }
        return sb.toString();
    }

    /**
     * Native character to ascii string.
     *
     * @param c native character
     * @return ascii string
     */
    private static String char2Ascii(char c) {
        if (c > 255) {
            StringBuilder sb = new StringBuilder();
            sb.append(PREFIX);
            int code = (c >> 8);
            String tmp = Integer.toHexString(code);
            if (tmp.length() == 1) {
                sb.append("0");
            }
            sb.append(tmp);
            code = (c & 0xFF);
            tmp = Integer.toHexString(code);
            if (tmp.length() == 1) {
                sb.append("0");
            }
            sb.append(tmp);
            return sb.toString();
        } else {
            return Character.toString(c);
        }
    }

    public static String ascii2Native(String str) {
        StringBuilder sb = new StringBuilder();
        int begin = 0;
        int index = str.indexOf(PREFIX);
        while (index != -1) {
            sb.append(str.substring(begin, index));
            sb.append(ascii2Char(str.substring(index, index + 6)));
            begin = index + 6;
            index = str.indexOf(PREFIX, begin);
        }
        sb.append(str.substring(begin));
        return sb.toString();
    }

    /**
     * @param str
     * @return
     * @author linzhengyu
     * @date 2014年9月17日
     */
    public static String strToNull(String str) {
        if (isEmpty(str)) {
            return null;
        } else {
            return str;
        }
    }

    public static void main(String[] args) {
        String unicodeStr = "{workContent:'\u6E05\u534E\u5927\u5B66\u5316\u5DE5\u7CFB\u57FA\u672C\u6709\u673A\u5408\u6210\u4E13\u4E1A\u5B66\u4E60'}";
        System.out.println(StringUtil.ascii2Native(unicodeStr));
    }
}
